<template>
  <div class="el-main-div">
    <div class="el-main-div-1">
      <div style="width: 12%; margin-right: 10px;">
        <el-input placeholder="请输入关键字(名字)" v-model="search">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <div style="width:200px margin-left=200px;">
        <el-button type="primary" plain @click="dialogformVisible = true">增加</el-button>

        <el-button type="danger" plain @click="openConfirm">批量删除</el-button>
      </div>

    </div>

    <div style="margin-left: 30px;">
      <el-table
        :data="tableData.filter(data => !search || data.customerName.toLowerCase().includes(search.toLowerCase()))"
        height=449  style=" width: 98%;" stripe
        :header-cell-style="{ background: '#F0F8FF', color: '#5E5F61', textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column type="index" width="80" label="序号">
        </el-table-column>
        <el-table-column prop="customerName" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="customerSex" label="性别" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.customerSex == 0" type="primary">男</el-tag>
            <el-tag v-if="scope.row.customerSex == 1" type="success">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerTelephone" label="电话号码">
        </el-table-column>
        <el-table-column prop="customerIdentity" label="身份证号">
        </el-table-column>
        <el-table-column prop="customerType" label="优惠类型">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.customerType == 0" type="primary">成人</el-tag>
            <el-tag v-if="scope.row.customerType == 1" type="success">儿童</el-tag>
            <el-tag v-if="scope.row.customerType == 2" type="info">学生</el-tag>
            <el-tag v-if="scope.row.customerType == 3" type="warning">军人</el-tag>
            <el-tag v-if="scope.row.customerType == 4" type="danger">残疾人</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" style="margin-right:10px;" @click="editCustomer(scope.row)"></el-button>
            <template>
              <el-popconfirm title="确定删除此乘车人吗？" icon="el-icon-info" icon-color="red" confirm-button-text='确定'
                cancel-button-text='不用了' @confirm=deleteCustomer(scope.row.customerIdentity,scope.row.customerName)>
                <el-button type="danger" icon="el-icon-delete" size="small" slot="reference"></el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="添加乘车人" :visible.sync="dialogformVisible" width="600px" style="font-weight: bold;">
      <el-form :model="addForm" style="margin-left: 90px;" :rules="rulesForm" ref="addForm">

        <el-form-item label="姓名：" label-width="100px" style="width: 320px;" prop="customerName">
          <el-input v-model="addForm.customerName" autocomplete="off" placeholder="请选择姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别：" label-width="100px" style="width: 320px;" prop="customerSex">
          <el-radio-group v-model="addForm.customerSex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="电话：" label-width="100px" style="width: 320px;" prop="customerTelephone">
          <el-input v-model="addForm.customerTelephone" autocomplete="off" placeholder="请选择电话">
            <template slot="prepend">(+86)</template></el-input>
        </el-form-item>

        <el-form-item label="身份证号：" label-width="100px" style="width: 320px;" prop="customerIdentity">
          <el-input v-model="addForm.customerIdentity" autocomplete="off" placeholder="请选择身份证号"></el-input>
        </el-form-item>

        <el-form-item label="优惠类型：" label-width="100px" style="width: 320px;" prop="customerType">
          <el-select v-model="addForm.customerType" placeholder="请选择优惠类型">
            <el-option label="成人" value=0>
              <el-tag>0-成人</el-tag>
            </el-option>
            <el-option label="儿童" value=1>
              <el-tag label="成人" type="success">1-儿童</el-tag>
            </el-option>
            <el-option label="学生" value=2>
              <el-tag type="info">2-学生</el-tag>
            </el-option>
            <el-option label="军人" value=3>
              <el-tag type="warning">3-军人</el-tag>
            </el-option>
            <el-option label="残疾人" value=4>
              <el-tag type="danger">4-残疾人</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setAddCustomer('addForm')">确 定</el-button>
        <el-button @click="restForm('addForm')">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog title="修改乘车人(身份证号不可修改)" :visible.sync="dialogformEditVisible" width="600px" style="font-weight: bold;">
      <el-form :model="editForm" style="margin-left: 90px;" :rules="rulesForm" ref="editForm">

        <el-form-item label="姓名：" label-width="100px" style="width: 320px;" prop="customerName">
          <el-input v-model="editForm.customerName" autocomplete="off" placeholder="请选择姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别：" label-width="100px" style="width: 320px;" prop="customerSex">
          <el-radio-group v-model="editForm.customerSex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="电话：" label-width="100px" style="width: 320px;" prop="customerTelephone">
          <el-input v-model="editForm.customerTelephone" autocomplete="off" placeholder="请输入电话">
            <template slot="prepend">(+86)</template></el-input>
        </el-form-item>

        <el-form-item label="身份证号：" label-width="100px" style="width: 320px;" prop="customerIdentity">
          <el-input v-model="editForm.customerIdentity" autocomplete="off" placeholder="请选择身份证号" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="优惠类型：" label-width="100px" style="width: 320px;" prop="customerType">
          <el-select v-model="editForm.customerType" placeholder="请选择优惠类型">
            <el-option label="成人" :value="0">
              <el-tag>0-成人</el-tag>
            </el-option>
            <el-option label="儿童" :value="1">
              <el-tag label="成人" type="success">1-儿童</el-tag>
            </el-option>
            <el-option label="学生" :value="2">
              <el-tag type="info">2-学生</el-tag>
            </el-option>
            <el-option label="军人" :value="3">
              <el-tag type="warning">3-军人</el-tag>
            </el-option>
            <el-option label="残疾人" :value="4">
              <el-tag type="danger">4-残疾人</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setUpdateCustomer('editForm')">确 定</el-button>
        <el-button @click="dialogformEditVisible=false">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { toast } from '../../../composables/util'
export default{
  name: "Customer",
  data() {
    return {
      // 按钮预加载
      loading: false,
      //添加对话框
      dialogformVisible: false,
      //修改对话框
      dialogformEditVisible: false,
      //确认框
      popVisible: true,
      search: '',
      addForm: {
        customerName: '',
        customerTelephone: '',
        customerIdentity: '',
        customerSex: '',
        customerType: '',
      },

      editForm: {
        customerName: '',
        customerTelephone: '',
        customerIdentity: '',
        customerSex: 0,
        customerType: '',
      },

      rulesForm: {
        customerName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        customerTelephone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 11, max: 11, message: '电话应为11位', trigger: ['blur', 'change'] }
        ],
        customerIdentity: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { min: 18, max: 18, message: '身份证号应为18位', trigger: ['blur', 'change'] }
        ],
        customerSex: [
          { required: true, message: '请选择性别', trigger: ['blur', 'change'] }
        ],
        customerType: [
          { required: true, message: '请选择优惠类型 ', trigger: ['blur', 'change'] }
        ]
      },
      listData: [],
      deleteId: []
    };
  },

  methods: {
    onQuery() {
      setTimeout(() => 
        this.FindAll(),100
      );
    },
    // 查询全部
    FindAll(){
      const findForm = {
        customerUser: this.userInfo.id
      }
      this.request.post('customer/getCustomer', findForm).then(
        response => {
          if (response.data.code === 1) {
            this.listData = response.data.data
            this.$message({
              message: '查询成功',
              type: 'success',
              duration: 1000
            });
          } else {
            this.$message({
              message: '查询出错: ' + response.data.msg,
              type: 'error',
              duration: 1000
            })
          }
        },
        error => {
          console.log(error.message)
        }
      )
    },
    // 清空表单
    restForm(form) {
      this.$refs[form].resetFields()
      this.dialogformVisible = false
    },
    // 转换数据
    exchangeForm(form){
      const customer = {
        customerUser: this.userInfo.id,
        customerName: form.customerName,
        customerTelephone: form.customerTelephone,
        customerIdentity: form.customerIdentity,
        customerSex: Number(form.customerSex),
        customerType: Number(form.customerType)
      }
      return customer
    },
    // 更新数据
    editCustomer(customer){
      this.dialogformEditVisible = true
      this.editForm = {
        customerName: customer.customerName,
        customerTelephone: customer.customerTelephone,
        customerIdentity: customer.customerIdentity,
        customerSex:customer.customerSex,
        customerType:customer.customerType
      }
      console.log(customer);
    },
    // 表单全面勾选
    handleSelectionChange(selection) {
      console.log(selection);
      var deleteData = selection;
      this.deleteId = deleteData.map((item) => {
        return item.id;
      });
      console.log(this.deleteId);
    },

    //  确认批量删除
    openConfirm() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          this.deleteBulkCustomer()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    
    setAddCustomer(formName) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addCustomer()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },

    addCustomer() {
      const customer = this.exchangeForm(this.addForm)
      this.request.post('customer/addCustomer', customer).then(
        response => {
          if (response.data.code === 1) {
            // this.dialogformVisible = false
            let msg = this.addForm.customerName + ",添加成功"
            toast("添加成功", this, msg)
            this.onQuery()
            this.restForm('addForm')
          } else {
            console.log(response);
            toast("添加失败", this, response.data.msg, "error")
          }
        },
        error => {
          console.log(error.message)
        }
      )
    },

    setUpdateCustomer(formName){
      this.$refs[formName].validate((valid) => {
          if (valid) {
            this.updateCustomer()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    
    updateCustomer(){
      const customer = this.exchangeForm(this.editForm)
      this.request.put('customer/updateCustomer',customer).then(
        response => {
          if (response.data.code === 1) {
            this.dialogformEditVisible = false
            let msg = customer.customerName + "更新成功"
            toast("更新成功", this, msg)
            this.onQuery()
          } else {
            console.log(response);
            toast("更新失败", this, response.data.msg, "error")
          }
      })
    },

    deleteCustomer(cuId, cuName) {
      const customer = {
        customerIdentity: cuId
      }
      this.popVisible = false
      console.log(customer);
      this.request.delete("customer/deleteCustomer", { params: { id: cuId } }).then(
        response => {
          if (response.data.code === 1) {
            let msg = cuName + ",删除成功"
            toast("删除成功", this, msg)
            this.onQuery()
          } else {
            toast("删除失败", this, response.data.msg, "error")
          }
        },
        error => {
          console.log(error.message)
        }
      )
    },

    deleteBulkCustomer(){
      console.log(this.deleteId);
      this.request.post("customer/deleteBulkCustomer",this.deleteId).then(
        response =>{
          if (response.data.code === 1){
            this.$message({
              message: '批量删除成功',
              type: 'success',
              duration: 1000
            });
            this.onQuery();
          }else{
            this.$message({
              message: '批量删除失败',
              type: 'error',
              duration: 1000
            });
          }  
        },
        error => {
          console.log("err:"+error.msg);
        }
      )
    },
  },

  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem('login_user'))
    this.onQuery()
  },

  computed:{
    tableData(){
      return this.listData
    }
  }

}
</script>

<style scoped>
.el-main-div {
  display: flex;
  flex-direction: column;
  /* border: 1px solid #e5e7eb; */
  width: 98%;
  height: 590px;
}

.el-main-div-1 {
  margin-top: 30px;
  margin-left: 30px;
  margin-bottom: 30px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  width: 100%;
}
</style>